﻿
        gothere.setOnLoadCallback(initialize);
        var directionsService = new google.maps.DirectionsService();
        var markersArray = [];
        var geocoder = new google.maps.Geocoder();
        var arrOfDestination = [];
        var directions;
        var wayptsGothere = [];
        var travelMode;
        var arrangedOutletName = [];
        var gothereArr = [];
        var map;

        document.getElementsByClassName = function (cl) {
            var retnode = [];
            var myclass = new RegExp('\\b' + cl + '\\b');
            var elem = this.getElementsByTagName('*');
            for (var i = 0; i < elem.length; i++) {
                var classes = elem[i].className;
                if (myclass.test(classes)) retnode.push(elem[i]);
            }
            return retnode;
        }; 

        function calculateDistance(lat1, lon1, lat2, lon2) {
            var R = 6371; // Radius of the earth in km
            var dLat = toRad(lat2 - lat1);  // Javascript functions in radians
            var dLon = toRad(lon2 - lon1);
            var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
        Math.sin(dLon / 2) * Math.sin(dLon / 2);
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            var d = R * c; // Distance in km
            return d;
        }

        function toRad(degree) {
            rad = degree * Math.PI / 180;
            return rad;
        }

        function loadMap() {

           
            travelMode = G_TRAVEL_MODE_TRANSIT;
        }

    

        function getDirections2() {
            var tbl = document.getElementById('itinerary');

            while (tbl && tbl.nodeName !== 'TABLE') {
                tbl = tbl.parentNode;
            }
            //dreamtcs, need to change this algorithm, currently supporting plain text
            for (i = 0; i <= tbl.rows.length - 1; i++) {
                for (j = 0; j <= tbl.rows[i].cells.length - 1; j++) {
                    if (tbl.rows[i].cells[j].innerText != "") {
                        arrOfDestination.push(tbl.rows[i].cells[j].innerText);
                    }
                }
                //dreamtcs, try to rearrange using TSP

                //do something to show directions
                calculateOptimalRoute(arrOfDestination);

                //dreamtcs, run once
                break;
            }


        } //end getDirections();

        function calculateOptimalRoute(arrOfDestination) {

            var waypts = [];

            var start = "";
            var end = "";
            if (arrOfDestination.length >= 2) {

                start = new google.maps.LatLng(arrOfDestination[0].toString().split("|")[2], arrOfDestination[0].toString().split("|")[1]);

                end = new google.maps.LatLng(arrOfDestination[arrOfDestination.length - 1].toString().split("|")[2], arrOfDestination[arrOfDestination.length - 1].toString().split("|")[1]);


                for (i in arrOfDestination) {

                    if (i == 0 || i == arrOfDestination.length - 1) {

                    }
                    else {

                        waypts.push({
                            location: new google.maps.LatLng(arrOfDestination[i].toString().split("|")[2], arrOfDestination[i].toString().split("|")[1]),
                            stopover: true
                        });

                    }
                }
            }

            var request = {
                origin: start,
                destination: end,
                waypoints: waypts,
                optimizeWaypoints: true,
                provideRouteAlternatives: true,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };

            if (arrOfDestination.length >= 2) {

                directionsService.route(request,
                function (response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        //directionsDisplay.setDirections(response);
                        var route = response.routes[0];
                        var summaryPanel = document.getElementById("gAddressList");
                        summaryPanel.innerHTML = "";
                        // For each route, display summary information.
                        if (route.legs.length > 0) {
                            summaryPanel.style.display = 'block';
                        } else {
                            summaryPanel.style.display = 'none';
                        }

                        var totalDistance = 0;

                        var summary = '';
                        arrangedOutletName = [];

                        for (var i = 0; i < route.legs.length; i++) {
                            var routeSegment = i + 1;

                            summary += '<div class="routeSegment">Route Segment: ' + routeSegment + '</div>';

                            //loop to see which one is nearest
                            var distance = 1000000;
                            var outletname = "";
                            var tbl = document.getElementById('itinerary');
                            for (k = 0; k <= tbl.rows.length - 1; k++) {

                                for (j = 0; j <= tbl.rows[k].cells.length - 1; j++) {
                                    if (tbl.rows[k].cells[j].innerText != "") {
                                        if (calculateDistance(route.legs[i].start_location.lat(), route.legs[i].start_location.lng(), tbl.rows[k].cells[j].innerText.toString().split("|")[2], tbl.rows[k].cells[j].innerText.toString().split("|")[1]) < distance) {
                                            outletname = tbl.rows[k].cells[j].innerText.toString().split("|")[0];
                                            distance = calculateDistance(route.legs[i].start_location.lat(), route.legs[i].start_location.lng(), tbl.rows[k].cells[j].innerText.toString().split("|")[2], tbl.rows[k].cells[j].innerText.toString().split("|")[1]);
                                        } //end if

                                    } //end if
                                } //end for
                            } //end for
                            if (i != route.legs.length - 1) {
                                arrangedOutletName.push(outletname);
                            }
                            else {
                                arrangedOutletName.push(outletname);
                            }
                            summary += '<div class="routeDetails"><b>From:</b> ' + outletname + '<br/>';
                            summary += route.legs[i].start_address + '<br/>';
                            summary += distance * 1000 + ' meters';
                            summary += route.legs[i].start_location.lat() + ',' + route.legs[i].start_location.lng() + '<br/>';

                            //loop to see which one is nearest
                            var distance = 1000000;
                            var outletname = "";
                            var tbl = document.getElementById('itinerary');
                            for (k = 0; k <= tbl.rows.length - 1; k++) {

                                for (j = 0; j <= tbl.rows[k].cells.length - 1; j++) {
                                    if (tbl.rows[k].cells[j].innerText != "") {
                                        if (calculateDistance(route.legs[i].end_location.lat(), route.legs[i].end_location.lng(), tbl.rows[k].cells[j].innerText.toString().split("|")[2], tbl.rows[k].cells[j].innerText.toString().split("|")[1]) < distance) {
                                            outletname = tbl.rows[k].cells[j].innerText.toString().split("|")[0];
                                            distance = calculateDistance(route.legs[i].start_location.lat(), route.legs[i].start_location.lng(), tbl.rows[k].cells[j].innerText.toString().split("|")[2], tbl.rows[k].cells[j].innerText.toString().split("|")[1]);
                                        } //end if

                                    } //end if
                                } //end for
                            } //end for
                            if (i != route.legs.length - 1) {


                            }
                            else {
                                arrangedOutletName.push(outletname);
                            }
                            summary += '<b>To:</b> ' + outletname + '<br/>';
                            summary += route.legs[i].end_address + '<br/>  ';
                            summary += distance * 1000 + ' meters';
                            summary += route.legs[i].end_location.lat() + ',' + route.legs[i].end_location.lng() + '<br/>  ';
                            summary += '<b>Distance:</b> ~ ' + route.legs[i].distance.text + '</div><br/> <br/> ';

                            //specific to gothere.sg
                            //while not last
                            //latlong
                            if (i != route.legs.length - 1) {
                                wayptsGothere.push(new GLatLng(route.legs[i].start_location.lat(), route.legs[i].start_location.lng()));

                            }
                            else {
                                wayptsGothere.push(new GLatLng(route.legs[i].start_location.lat(), route.legs[i].start_location.lng()));
                                wayptsGothere.push(new GLatLng(route.legs[i].end_location.lat(), route.legs[i].end_location.lng()));
                            }
                           
                            //end specific to gothere.sg

                            totalDistance += route.legs[i].distance.value;

                        }
                      
                      
                        directions.loadFromWaypoints(wayptsGothere, { travelMode: travelMode });
                        summary += '<div class="routeSegment">Total Distance: ' + Math.round((totalDistance / 1000) * 1000) / 1000 + ' km</div>';
                        summaryPanel.innerHTML = summary;
                      
            
                    } else {
                        alert('Service cannot calculate route');
                    }
                });
            }

        } //end calculateOptimalRoute();


        gothere.load("maps");

        function initialize() {
            if (GBrowserIsCompatible()) {
                // Create the Gothere map object.
                map = new GMap2(document.getElementById("map"));
                // Set the center of the map.
                map.setCenter(new GLatLng(1.362083, 103.819836), 11);
                // Add zoom controls on the top left of the map.
                map.addControl(new GSmallMapControl());
                // Add a scale bar at the bottom left of the map.
                map.addControl(new GScaleControl());
                directions = new GDirections(map, document.getElementById("panel"));
                GEvent.addListener(directions, "addoverlay", function () {


                    gothereArr = [];
                    gothereArr = document.getElementsByClassName('gothereadd');

                    for (m = 0; m <= gothereArr.length - 1; m++) {

                        gothereArr[m].innerText = arrangedOutletName[m] + ': nearest civic address is ' + gothereArr[m].innerText;

                    }
                });
                GEvent.addListener(directions, "erroer", function () { alert("Unable to retrieve directions from gothere.sg, latitude and longitude might be out of range"); });
            }
        }

        function getDirections() {
            var mode = document.getElementsByName("mode").mode[document.getElementsByName("mode").mode.selectedIndex].value;
            switch (mode) {
                case "pt":
                    travelMode = G_TRAVEL_MODE_TRANSIT;
                    break;
                case "t":
                    travelMode = G_TRAVEL_MODE_TAXI;
                    break;
                case "d":
                default:
                    travelMode = G_TRAVEL_MODE_DRIVING;
                    break;
            }

            gothereArr = [];
            arrangedOutletName = [];
            arrOfDestination = [];
            wayptsGothere = [];
            getDirections2();

          
        }
        
